package org.aaa.exp05;

import lombok.extern.slf4j.Slf4j;

import static java.lang.Thread.sleep;

/**
 * @author Richard Wang
 * @date 2025/7/3 22:59
 */
@Slf4j(topic = "c.TestJoin")
public class TestJoin {
    static int r = 0;
    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) throws InterruptedException {
//        test01();
//        test02();
        test03();
    }

    private static void test03() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                sleep(2000);
                r = 10;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        t1.start();
        log.debug("join start");
        long start = System.currentTimeMillis();
//        t1.join(1500);
        t1.join(2500);
        long end = System.currentTimeMillis();
        log.debug("r:{} cost: {} ms", r, end - start);
    }


    private static void test02() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                sleep(1000);
                r1 = 2;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            try {
                sleep(2000);
                r2 = 3;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t2");
        t1.start();
        t2.start();
        log.debug("join start");
        long start = System.currentTimeMillis();
//        t1.join();
//        log.debug("t1 join end");
//        t2.join();
//        log.debug("t2 join end");

        t2.join();
        log.debug("t2 join end");
        t1.join();
        log.debug("t1 join end");

        long end = System.currentTimeMillis();
        log.debug("r1:{} r2:{} cost: {} ms", r1, r2, end - start);
    }

    private static void test01() throws InterruptedException {
        log.debug("开始");
        Thread t1 = new Thread(() -> {
            try {
                log.debug("开始");
                sleep(1);
                log.debug("结束");

                r = 10;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }, "t1");
        t1.start();
        t1.join();

        log.debug("结果为：" + r);
        log.debug("结束");
    }
}
